# -*- coding:UTF-8 -*-
import requests
import pytest
import json
import model.Base64ConvertTo as Base64ConvertTo
import model.request_xl as request_xl

class requestAPI(object):
    # init
    def __init__(self, token, os_version, log):
        self.token = token
        self.t_headers = {
            'token': token,
            'os_version': os_version,
        }
        self.log = log

    # 请求接口
    def execute(self, caseFileName, sheetname, ApiPurpose):
        try:
            # 读取case配置文件并获得对应值
            rxl = request_xl.request_xl(caseFileName, self.log)
            api_values = rxl.get_xl(sheetname, ApiPurpose)
            self.API_Host = api_values[2]
            self.Request_URL = api_values[3]
            self.Request_Method = api_values[4]
            self.Request_Data = eval(api_values[6])
            self.Encryption = api_values[7]
            # 检查结果点
            # self.CheckPoint = api_values[8]
            t_url = self.API_Host + self.Request_URL
            t_headers = self.t_headers
            if self.Encryption == 'BASE64':
                self.log.info("== data 进行 base64加密==")
                data = Base64ConvertTo.Base64Convert().base64Encode(self.Request_Data)
                response = requests.request(self.Request_Method, t_url, headers=t_headers, params={'data': data})
            # elif self.Encryption == 'MD5':
            #     data = Base64ConvertTo.Base64Convert().convert_to_md5(self.Request_Data, self.token)
            #     response = requests.request(t_method, t_url, headers=t_headers, params={'data': data})
            elif self.Encryption == 'BASE64+MD5':
                self.log.info('data进行base64+md5加密')
                data = Base64ConvertTo.Base64Convert().base64Encode(self.Request_Data)
                sign = Base64ConvertTo.Base64Convert().convert_to_md5(data, self.token)
                response = requests.request(self.Request_Method, t_url, headers=t_headers, params={'data': data, 'sign': sign})
            else:
                self.log.info('不加密data')
                response = requests.request(self.Request_Method, t_url, headers=t_headers, params={'data': self.Request_Data})
            # 直接返回json
            # return response.text
            self.log.info(response.text)
            self.log.info("request API end")
            api_result = json.loads(response.text)
            return api_result
        except Exception as e:
            self.log.info("===== request API error =====%s" % e)
            pytest.fail("CASE FAIL")
            return 0

    # def APIActive(self):
    #     return self.Active
